package cn.edu.scau.cmi.wuzhenxin.hibernate.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.edu.scau.cmi.wuzhenxin.hibernate.domain.Student;

public class StudentDAOByHibernate extends BaseHibernateDao {
	private static final Logger log = LoggerFactory.getLogger(StudentDAOByHibernate.class);
	// property constants
	public static final String NAME = "name";

	private Session session = getSession();//获取session
	// insert new student
	public boolean save(Student student) {//存储学生
		log.debug("saving teacher instance");
		try {
			Transaction transaction = session.beginTransaction();
			session.save(student);
			transaction.commit();
			log.debug("save successful");
			return true;
		} catch (RuntimeException e) {
			log.error("get failed", e);
			throw e;
		} 
	}

	//find student by id
	public Student findById(Integer id) {//根据id获取学生实例
		log.debug("getting Student instance with id: #" + id);
		try {
			Student instance = (Student) session.get(
					"cn.edu.scau.cmi.wuzhenxin.hibernate.domain.Student", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get student failed", re);
			throw re;
		}
	}
	
	//find all student
	public List<Student> findAll(){//输出学生清单
		log.debug("getting all Student instance");
		try {
			String queryString = "from Student";
			Query queryObject = session.createQuery(queryString);
			log.debug("get all student successful");
			List<Student> list = queryObject.list();
			return list;
		} catch (RuntimeException re) {
			log.error("get all student failed", re);
			throw re;
		} 
	}
	
	//modify student by id
	public boolean updateById(Student student) {//根据id修改学生的其它信息
		log.debug("updating Student instance with id: #" + student.getId());
		try {
			Transaction transaction = session.beginTransaction();
			session.saveOrUpdate(student);
			transaction.commit();
			log.debug("update successful");
			return true;
		} catch (RuntimeException re) {
			log.error("update student failed", re);
			throw re;
		}
	}
	
	//delete student by id
	public boolean deleteById(Student student) {
		log.debug("deleting Student instance with id: #" + student.getId());
		try {
			Transaction transaction = session.beginTransaction();
			session.delete(student);
			transaction.commit();
			log.debug("delete successful");
			return true;
		} catch (RuntimeException re) {
			log.error("delete student failed", re);
			throw re;
		}
	}

}
